﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BulletOnRails4NET.Controllers;
using GeneCMS.Models.physical;
using BulletOnRails4NET.Models;
using Suteki.Common.Repositories;
using BulletOnRailsNET.Models.FormBuilder;
using GeneCMS.Models.View;
using System.Security.Principal;

namespace GeneCMS.Controllers
{
    public class GenePublicController : Controller
    {

        public static string EscapeJS(string str)
        {
            //return str.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("<", "OPENTAGGENE").Replace(">", "CLOSETAGGENE").Replace("!--", "COMENTGENE");
            return str.Replace("'", "\\'").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "");
        }

        public GeneCMS.Models.logical.Website GetUserWebsite()
        {
            return GetWebsite(GetUserWebsiteID(User));
        }

        public int GetUserWebsiteID(IPrincipal webuser)
        {
            Repository<Usr> user_data = new Repository<Usr>();
            var user = user_data.GetAll().Where(u => u.Username == webuser.Identity.Name).SingleOrDefault();
            return user.WebsiteID.Value;
        }

        /// <summary>
        /// Builds a logicalWebsite object that contains the system-wide
        /// preferences and correct links to editing and template folders.
        /// </summary>
        /// <param name="website_id"></param>
        /// <returns></returns>
        public GeneCMS.Models.logical.Website GetWebsite(int website_id)
        {
            Repository<GeneCMS.Models.physical.Website> website_data = new Repository<GeneCMS.Models.physical.Website>();
            var cms_website_data = website_data.GetById(website_id);

            GeneCMS.Models.logical.Website cms_website = new GeneCMS.Models.logical.Website()
            {
                PreviewBasePath =
                    HttpContext.Server.MapPath(PathResolver.GetSiteRoot() + "preview/" + cms_website_data.ID + "/"),
                EditingBasePath =
                    HttpContext.Server.MapPath(PathResolver.GetSiteRoot() + "editing/" + cms_website_data.ID + "/"),
                InjectCodeFilePath =
                HttpContext.Server.MapPath(PathResolver.GetSiteRoot() + "templates/EditCodeToInject.htm"),
                WebsiteTemplatePath =
                    HttpContext.Server.MapPath(PathResolver.GetSiteRoot() + "templates/" + cms_website_data.TemplateFolder + "/" + cms_website_data.TemplateMainFile),
                WebsiteTemplateFolder =
                HttpContext.Server.MapPath(PathResolver.GetSiteRoot() + "templates/" + cms_website_data.TemplateFolder + "/"),
                WebsiteID = cms_website_data.ID,
                WebsiteProductionPath = cms_website_data.ProductionFilePath
            };
            return cms_website;
        }
    }
}